package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"lib/http"
	"lib/id"
	"lib/structs/enum"
	"lib/structs/lms"
	"lib/structs/tables"
	"lms/global"
	"lms/repository"
	"lms/service"
)

var KnowledgeApi = new(knowledgeApi)

type knowledgeApi struct {
}

func (a knowledgeApi) Add(c *gin.Context) {
	var in lms.AddKnowledge
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	self := http.GetCurrentUser(c)
	m := &tables.Knowledge{
		Id:             id.GetSnowId(),
		Name:           in.Name,
		Describe:       in.Describe,
		EmbeddingModel: in.EmbeddingModel,
		ChunkSize:      in.ChunkSize,
		ChunkOverlap:   in.ChunkOverlap,
		AutoCreateInfo: tables.AutoCreateInfo{
			Creator:   self.Nickname,
			CreatorId: self.UserID,
		},
	}
	if err := repository.KnowledgeDB.Create(m); err != nil {
		http.BadWithDB(c, err)
		return
	}
	http.OK204(c)
}

func (a knowledgeApi) Delete(c *gin.Context) {
	in := struct {
		Id int64 `uri:"id"`
	}{}
	if err := c.ShouldBindUri(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	d, err := repository.KnowledgeDB.FindById(in.Id)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	self := http.GetCurrentUser(c)
	if d.CreatorId != self.UserID {
		http.BadWithCode(c, enum.ErrorMap.AccessDeniedForCreate)
		return
	}
	err = service.KnowledgeService.DeleteById(in.Id)
	if err != nil {
		global.LmsLog.Error("删除知识库时发生错误", err)
		http.BadWithCode(c, enum.ErrorMap.DeleteKnowledgeErr)
		return
	}
	http.OK204(c)
}

func (a knowledgeApi) List(c *gin.Context) {
	in := struct {
		Name string `form:"name"`
	}{}
	if err := c.ShouldBindQuery(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	li, err := repository.KnowledgeDB.List(in.Name)
	if err != nil {
		http.BadWithDB(c, err)
	}
	http.Ok(c, li)
}

func (a knowledgeApi) BindFile(c *gin.Context) {
	var in lms.DocEmbedding
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c)
		return
	}
	self := http.GetCurrentUser(c)
	li, err := repository.CoursewareDb.FindSelfByIds(in.CoursewareIds, self.UserID)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	know, err := repository.KnowledgeDB.FindById(in.KnowledgeId)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	err = repository.CoursewareDb.UpdateCoursewareVectorStatus(in.CoursewareIds, enum.FileVectorStatus.Being)
	if err != nil {
		http.BadWithDB(c, err)
		return
	}
	go func() {
		if err := service.CoursewareService.EmbeddingCourseware(context.Background(), li, know); err != nil {
			global.LmsLog.Error("EmbeddingCourseware err:", err)
			return
		}
	}()
	http.OK204(c)
}

func (a knowledgeApi) ChatForWS(c *gin.Context) {
	err := service.WSService.OllamaChat(c)
	if err != nil {
		http.BadWithCode(c, enum.ErrorMap.OllamaConnErr)
		return
	}
	http.OK204(c)
}
